<?php

namespace app\modules\hr\modules\pick\controllers;

use app\controllers\BaseController;
use app\data\PickData;

class DefaultController extends BaseController
{
    public $layout = '/employee';
    private $_pickManager;
    private $department_id;

    public function init()
    {
        date_default_timezone_set("America/Los_Angeles");
        parent::init();
        $this->_pickManager = \YII::$app->mydi->get("app\lib\logic\PickLogicInterface");
        $this->getDepartmentID();
    }

    public function indexViewData()
    {
        $firstDay = date('Y-m-01', time());
        $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
        $date['s_date_start'] = $firstDay;
        $date['s_date_end'] = $lastDay;
        $remind = $this->_pickManager->remind();
        $auth = $this->_pickManager->getGroupOrDepartmentID();
        $pickAffectedNumber = $this->_pickManager->pickAffectedNumber();
        $viewAffectedStaff = $this->_pickManager->viewAffectedStaff();
        if ($viewAffectedStaff) {
            $affectedStaffNumber = $this->_pickManager->affectedStaffNumber();
        } else {
            $affectedStaffNumber = 0;
        }
        $accredit = $this->_pickManager->That();
        $buttonAuth = $this->_pickManager->auth();
        return ['date' => $date, 'remind' => $remind, 'auth' => $auth, 'accredit' => $accredit, 'buttonAuth' => $buttonAuth, 'pickAffectedNumber' => $pickAffectedNumber, 'viewAffectedStaff' => $viewAffectedStaff, 'affectedStaffNumber' => $affectedStaffNumber];
    }

    public function actionIndex()
    {
        $data = $this->indexViewData();
        return $this->render("index", $data);
    }

    public function actionPerformance()
    {
        $data = $this->indexViewData();
        return $this->render("performance", $data);
    }

    public function actionRight()
    {
        $data = $this->indexViewData();
        return $this->render("right", $data);
    }

    //展示列表
    public function actionList()
    {
        $get = \Yii::$app->request->get();
        $where['s_date_start'] = empty($get['s_date_start']) ? strtotime(date("Y-m", time())) - 1 : strtotime($get['s_date_start']) - 1;
        $where['s_date_end'] = empty($get['s_date_end']) ? strtotime(date('Y-m', strtotime('+1 month'))) : strtotime($get['s_date_end']) + 86400;
        $column = empty($get['column']) ? 2 : $get['column'];
        $data = $this->_pickManager->getDepartmentList($where, $column);
        $data = $this->_pickManager->filterField($data, ['id', 'created', 'group_name', 'department_name', 'type_name', 'level1', 'level2', 'name_en_long', 'name_cn_long', 'content']);
        return $this->renderJson($data);
    }

    //添加摘錯頁面
    public function actionAdd()
    {
        return $this->render("add");
    }

    //添加摘錯頁面提交
    public function actionInsert()
    {
        $post = \Yii::$app->request->post();
        $result = $this->_pickManager->add($post);
        if ($result == false)
            return $this->renderJson(["status" => 0, "info" => "添加失败"]);
        return $this->renderJson(["status" => 1, "info" => "添加成功"]);
    }

    //獲取部门单一類型
    public function actionGettype()
    {
        $pid = \Yii::$app->request->get('pid');
        $department_id = \Yii::$app->request->get('department_id');
        $list = $this->_pickManager->getTypeList($pid, $department_id, true);
        $list = $this->_pickManager->filterField($list, ['id', 'name', 'pid']);
        return $this->renderJson($list);
    }

    //獲取全部類型
    public function actionGetalltype()
    {
        $where = array(
//			'or',
//			['=',"belong_department",$this->department_id],
//			['=',"belong_department",'0'],
//			['=',"belong_department",'1'],
        );
        $list = $this->_pickManager->getTypeAllList($where);
        $list = $this->_pickManager->filterField($list, ['id', 'name', 'pid', 'belong_department']);
        return $this->renderJson($list);
    }

    //获取四大类
    public function actionGetfourtype()
    {
        $where = ['=', "belong_department", '1'];
        $list = $this->_pickManager->getTypeAllList($where);
        return $this->renderJson($list);
    }

    //獲取警告等級
    public function actionGettagview()
    {
        return $this->renderJson(PickData::getTagView());
    }

    //獲取全部評級
    public function actionGetallrating()
    {
        $where = ['NOT', ['is_del' => '0']];
        $data = $this->_pickManager->getRatingList($where);
        return $this->renderJson($data);
    }

    //获取部门评级
    public function actionGetrating()
    {
        $department_id = \Yii::$app->request->get('department_id');
        $where = [
            'and',
            ['=', "belong_department", empty($department_id) ? $this->department_id : $department_id],
            ['NOT', ['is_del' => '0']]
        ];
        $data = $this->_pickManager->getRatingList($where);
        return $this->renderJson($data);
    }

    //獲取部門id
    protected function getDepartmentID()
    {
        $user_id = strtoupper(\Yii::$app->session["userInfo"]["UserID"]);
        $where = "user_id = '$user_id'";
        $department = $this->_pickManager->getDepartmentID($where);
        $this->department_id = $department['department_id'];
    }

    //展示小組條目
    public function actionTeamentry()
    {
        $firstDay = date('Y-m-d');
        $time['T_date_start'] = date("Y-m-d", strtotime("-4 day"));
        $time['T_date_end'] = $firstDay;
        $remind = $this->_pickManager->remind();
        $data = $this->_pickManager->getGroupOrDepartmentID();
        if ((($data['type'] == 4 || $data['type'] == 8) && $this->_pickManager->getPerformance()) || $data['type'] == '*')
            return $this->render("teamentry", ['department' => 1, 'time' => $time, 'remind' => $remind]);
        return $this->render("teamentry", ['time' => $time, 'remind' => $remind]);
    }

    //獲取小組條目數據
    public function actionGetteamentrylist()
    {
        $get = \Yii::$app->request->get();
        $time['T_date_start'] = empty($get['T_date_start']) ? strtotime("-4 day") - 1 : strtotime($get['T_date_start']) - 1;
        $time['T_date_end'] = empty($get['T_date_end']) ? strtotime("+1 day") : strtotime($get['T_date_end']) + 86400;
        $user_idS = $this->_pickManager->getAuthUserId();
        $where = array(
            'and',
            ['>', 'cn_pick.created', $time['T_date_start']],
            ['<', 'cn_pick.created', $time['T_date_end']],
            ['=', 'cn_pick.is_del', 1],
            ['cn_pick.user_id' => $user_idS],
        );
        $data = $this->_pickManager->getAllPickList($where);
        return $this->renderJson($data);
    }

    //更新小组条目
    public function actionUpdatateamentry()
    {
        $post = \Yii::$app->request->post();
        $post['created'] = preg_replace('/GMT.*?\)/', '', $post['created']);
        if (!empty($post['affected_department']) && is_array($post['affected_department'])) {
            foreach ($post['affected_department'] as $k => $v) {
                if (is_array($v) && isset($post['affected_department'][$k]['id']))
                    $post['affected_department'][$k] = $post['affected_department'][$k]['id'];
            }
            $post['affected_department'] = implode('.', $post['affected_department']);
        } else {
            $post['affected_department'] = "";
        }
        if (!empty($post['affected_group']) && is_array($post['affected_group'])) {
            foreach ($post['affected_group'] as $k => $v) {
                if (is_array($v) && isset($post['affected_group'][$k]['id']))
                    $post['affected_group'][$k] = $post['affected_group'][$k]['id'];
            }
            $post['affected_group'] = implode('.', $post['affected_group']);
        } else {
            $post['affected_group'] = "";
        }
        $result = $this->_pickManager->UpdataTeamentry($post);
        if (empty($result['info']))
            $result['info'] = "評級失敗！";
        if ($result['status'] == false)
            return $this->renderJson(["status" => 0, "info" => $result['info']]);
        return $this->renderJson(["status" => 1, "info" => "評級成功！"]);
    }

    //删除小组条目
    public function actionDestroyteamentry()
    {
        $sID = \Yii::$app->request->post('id');
        $result = $this->_pickManager->DestroyTeamentry($sID);
        if ($result)
            return $this->renderJson(["status" => 1, "msg" => "删除成功！"]);
        return $this->renderJson(["status" => 0, "msg" => "删除失败！"]);
    }

    /**
     * 小組條目 獲取被影響部門list
     * key value group
     */
    public function actionTeamentryaffecteddepartment()
    {
        $departmentId = \Yii::$app->request->get('department_id');
        $departments = $this->filterDepartment([$departmentId]);
        return $this->renderJson($departments);
    }

    /**
     *  被影響人：情況1、根據獲取權限獲取，部門list 情況2、獲取全部權限之外的，部門list 情況3、獲取除發績效部門外所有部門
     * filter 0 ：獲取不存在權限的部門 1：獲取存在權限的部門 其他：獲取排除發績效的全部部門
     * @return string
     */
    public function actionPickaffecteddepartment()
    {
        $departmentId = \Yii::$app->request->get('department_id');
        $filter = \Yii::$app->request->get('filter');
        $departments = $this->filterDepartment([$departmentId]);
        $trueAffectDepartment = $this->_pickManager->getViewOneAffectDepartment();
        if ($filter == '1') {
            foreach ($departments as $k => $v) {
                if (!in_array($v['id'], $trueAffectDepartment['affected_department'])) {
                    unset($departments[$k]);
                }
            }
        } elseif ($filter == '0') {
            foreach ($departments as $k => $v) {
                if (in_array($v['id'], $trueAffectDepartment['affected_department'])) {
                    unset($departments[$k]);
                }
            }
        }
        return $this->renderJson(array_values($departments));
    }

    /***
     * 被影響人：情況1、根據獲取權限獲取，組list 情況2、獲取全部權限之外的，組list 情況3、獲取所有組
     * filter 0 ：獲取不存在權限的組別 1：獲取存在權限的組別 其他：獲取全部組別
     * @return string
     */
    public function actionPickaffectedgroup(){

        $affectedDepartment = \Yii::$app->request->post('affectedDepartment');
        $filter = \Yii::$app->request->post('filter');
        $unitData = [];
        if ($affectedDepartment && is_array($affectedDepartment)) {
            $where = [
                'and',
                ['=', 'cn_unit.type', 4],
                ['=', 'cn_unit.is_active', 1],
                ['=', 'pp.is_active', 1],
                ['=', 'p.is_active', 1],
                ['NOT', ['pp.id' => null]],
                ['in','cn_unit.id',$affectedDepartment]
            ];
            $unitData = $this->_pickManager->getAffectedGroup($where);
            if (in_array($filter,['0','1'])) {
                $auth = $this->_pickManager->getSummaryPermissions();
                $department = empty($auth['affected_department']) ? [] : explode('.', $auth['affected_department']);
                $group = empty($auth['affected_group']) ? [] : explode('.', $auth['affected_group']);
                $authGroup = $this->_pickManager->canSelectAffectedGroup($department,$group);
                if ($filter == '0') {
                    foreach ($unitData as $k => $v) {
                        if (in_array($v['id'], $authGroup)) {
                            unset($unitData[$k]);
                        } else {
                            $unitData[$k]['group'] = str_replace("<br>", "", $v['group']);
                        }
                    }
                    $unitData = array_values($unitData);
                } elseif ($filter == '1') {
                    foreach ($unitData as $k => $v) {
                        if (!in_array($v['id'], $authGroup)) {
                            unset($unitData[$k]);
                        } else {
                            $unitData[$k]['group'] = str_replace("<br>", "", $v['group']);
                        }
                    }
                    $unitData = array_values($unitData);
                }
            }else{
                foreach ($unitData as $k => $v) {
                    $unitData[$k]['group'] = str_replace("<br>", "", $v['group']);
                }
            }
        }
        return $this->renderJson($unitData);
    }

    /**
     *  強制過濾部門：中國WXF不顯示IS部；美國只顯示物流部，EHS和HR
     * @param array $departmentId 排除的部門ID
     * @return array
     */
    function filterDepartment($departmentId = [])
    {
        $country = $this->_pickManager->company(8);
        $i = 0;
        $departments = [];
        foreach ($country as $k => $v) {
            $department = $this->_pickManager->child($v['id']);
            foreach ($department as $k1 => $v1) {
                if (in_array($v1['id'], $departmentId)) {
                    continue;
                }
                if ($v1['country_code'] == 2) {
                    if (!in_array($v1['id'], ['8BC159AD-CE90-4237-91B1-7948B54D2D30', '1DB77233-00D5-4B4E-B27D-DECF518AC931', '1842970D-3C7B-42D5-9615-FF8D04F9B5A3'])) {
                        continue;
                    }
                } elseif ($v1['country_code'] == 1) {
                    if (in_array($v1['id'], ['6E9CDA60-B186-4124-9A76-16252FB346FF'])) {
                        continue;
                    }
                }
                $departments[$i]['id'] = $v1['id'];
                $departments[$i]['name'] = str_replace("<br>", "", $v1['unit_name']);
                $departments[$i]['group'] = str_replace("<br>", "", $v['unit_name']);
                $departments[$i]['groupId'] = $v['id'];
                $i++;
            }
        }
        return $departments;
    }

    /*-------------------------------------------- 總匯界面 START --------------------------------------------------------*/
    public function actionSummary()
    {
        $firstDay = date('Y-m-01', time());
        $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
        $date['su_date_start'] = $firstDay;
        $date['su_date_end'] = $lastDay;
        $date['management'] = $this->_pickManager->management();
        return $this->render("summary", ['date' => $date]);
    }

    public function actionGetsummarylist()
    {
        $get = \Yii::$app->request->get();
        $where['su_date_start'] = empty($get['su_date_start']) ? strtotime(date("Y-m", time())) - 1 : strtotime($get['su_date_start']) - 1;
        $where['su_date_end'] = empty($get['su_date_end']) ? strtotime(date('Y-m', strtotime('+1 month'))) : strtotime($get['su_date_end']) + 86400;
        $where['management'] = empty($get['management']) ? false : $get['management'] == 'true' ? true : false;
        $data = $this->_pickManager->getSummaryList($where);
        $data = PickData::toTimeDate($data);
        $data = $this->_pickManager->filterField($data, ['id', 'created', 'content', 'column_name', 'group_name', 'department_name', 'type_name', 'level1_name', 'level2_name', 'name_en_long', 'tag', 'rating']);
        $aTag = PickData::getTagView();
        foreach ($data as $k => $v) {
            foreach ($aTag as $v1) {
                if ($v1['id'] == $data[$k]['tag']) {
                    $data[$k]['tag'] = $v1['name'];
                }
            }
        }
        return $this->renderJson($data);
    }
    /*-------------------------------------------- 總匯界面 END ----------------------------------------------------------*/
    //个人
    public function actionPersonal()
    {
        $remind = $this->_pickManager->remind();
        $data = date("Y-m");
        return $this->render("personal", ['remind' => $remind, 'data' => $data]);
    }

    public function actionPersonallist()
    {
        $psl_date_month = \Yii::$app->request->get('psl_date_month');
        $month = empty($psl_date_month) ? date("Y-m", time()) : str_replace('/', '-', $psl_date_month);
        $time['start'] = strtotime($month) - 1;
        $time['end'] = strtotime("$month +1 month -1 day") + 86400;
        $data = $this->_pickManager->getPersonalList($time);
        $data = $this->_pickManager->filterField($data, ['content', 'rating_open', 'created', 'deductions_situation', 'early_number', 'id', 'rating_name', 'rating_points']);
        return $this->renderJson($data);
    }

    public function actionPersonearlytimelist()
    {
        $data = $this->_pickManager->getPersonEarlyTimeList();
        return $this->renderJson($data);
    }

    //计算本月扣款金额
    public function actionGetdeductions()
    {
        $psl_date_month = \Yii::$app->request->get('psl_date_month');
        $month = empty($psl_date_month) ? date("Y-m", time()) : str_replace('/', '-', $psl_date_month);
        $time['start'] = strtotime($month) - 1;
        $time['end'] = strtotime("$month +1 month -1 day") + 86400;
        $user_id = strtoupper(\Yii::$app->session["userInfo"]["UserID"]);
        $where = $time;
        $where['user_id'] = $user_id;
        $data = $this->_pickManager->getPickDeductionsSum($where);
        if (empty($data[0]['moneySum']))
            return $this->renderJson([0]);
        return $this->renderJson($data[0]['moneySum']);
    }

    //申請修改早班時間
    public function actionModifyearlytime()
    {
        $get = \Yii::$app->request->get();
        if (empty($get['early_time']) && empty($get['cn_early_time_id']))
            return false;
        $get['early_time'] = preg_replace('/GMT.*?\)/', '', $get['early_time']);
        $time = strtotime(date("Y-m-d", strtotime($get['early_time'])));
        $week = date("w", $time);
        if ($week != 5)
            return $this->renderJson(["status" => 0, "info" => "所申请时间不符合要求！"]);

        $bool = $this->_pickManager->repeatEarlyTime($time);
        if ($bool)
            return $this->renderJson(["status" => 0, "info" => "申请时间已存在早班申请！"]);
        $earlyEndTime = strtotime(date("Y-m-d", $time) . "+ 1 days");
        $earlyTime = [
            'and',
            ['=', 'cn_pick.user_id', strtoupper(\Yii::$app->session["userInfo"]["UserID"])],
            ['>=', 'cn_early_time.early_time', $time],
            ['<', 'cn_early_time.early_time', $earlyEndTime],
            ['=', 'cn_pick.is_del', 1],
            ['=', 'overdue', 0]
        ];
        $TwoData = $this->_pickManager->getEarlyTimePickStaff($earlyTime, false);
        if (!empty($TwoData))
            return $this->renderJson(["status" => 0, "info" => "申请时间已存在,早班日期！"]);


        // $OneData = $this->_pickManager->getEarlyTime(['=','id',$get['cn_early_time_id']]);
        // if($OneData[0]['early_time']<time()){
        //     return $this->renderJson(["status"	=>	0,"info"=>	"申请失败",'situation'=>'101']);
        // }
        $where['cn_early_time_id'] = $get['cn_early_time_id'];
        $res = $this->_pickManager->getEarlyTimeNumber($where);
        if ($res != false)
            return $this->renderJson(["status" => 0, "info" => "当前审核尚未审核完成，不可以重复申请！"]);
        $where['early_time'] = $time;
        $result = $this->_pickManager->addEarlyTimeApply($where);
        if ($result == false)
            return $this->renderJson(["status" => 0, "info" => "申请失败！", 'situation' => '102']);
        return $this->renderJson(["status" => 1, "info" => "申请成功"]);
    }

    public function actionPersonalearlytime()
    {
        return $this->render("personalearlytime");
    }

    /*-------------------------------------------- 部门类别编辑 START------------------------------------------------------*/
    public function actionDepartmenttypeedit()
    {
        return $this->render("departmenttypeedit");
    }

    public function actionDepartmenttypeeditlist($type = true)
    {
        $data = $this->_pickManager->departmentTypeEdit();
        if ($type) {
            return $this->renderJson($data[1]);
        } else {
            return $this->renderJson($data[0]);
        }

    }

    //添加部门类别
    public function actionAdddepartmenttypeedit()
    {
        $post = \Yii::$app->request->post();
        if (!empty($post['id'])) {
            return $this->renderJson(['status' => 0, 'msg' => '请刷新一下页面！']);
        }
        if (empty($post['name'])) {
            return $this->renderJson(['status' => 0, 'msg' => '请填写类别名！']);
        }
        $data['name'] = $post['name'];
        if (empty($post['pid'])) {
            return $this->renderJson(['status' => 0, 'msg' => '请刷新一下页面！']);
        }
        $data['pid'] = $post['pid'];
        if (!is_numeric($post['sort'])) {
            return $this->renderJson(['status' => 0, 'msg' => '排序要填写数字！']);
        }
        $data['sort'] = $post['sort'];
        $at = $this->_pickManager->getSummaryPermissions();
        if (empty($at))
            return false;
        if (empty($at['department_type_edit']))
            return false;
        $res = $this->_pickManager->addDepartmentType($data);
        if ($res == false)
            return $this->renderJson(['status' => 0, 'msg' => '添加失败，请刷新后重新尝试！']);
        return $this->renderJson(['status' => 1, 'msg' => '添加成功']);

    }

    //更新类别
    public function actionUpdatedepartmenttypeedit()
    {
        $post = \Yii::$app->request->post();
        if (empty($post['id']))
            return $this->remderJson(['status' => 0, 'msg' => '请刷新一下页面！']);
        $data['id'] = $post['id'];
        if (empty($post['name']))
            return $this->remderJson(['status' => 0, 'msg' => '请填写类别名称！']);
        $data['name'] = $post['name'];
        if (!is_numeric($post['sort'])) {
            return $this->renderJson(['status' => 0, 'msg' => '排序要填写数字！']);
        }
        $data['sort'] = $post['sort'];
        $data['status'] = $post['status'] == 'true' ? 1 : 0;
        $at = $this->_pickManager->getSummaryPermissions();
        if (empty($at))
            return false;
        if (empty($at['department_type_edit']))
            return false;
        if ($post['status'] == 'false') {
            /*  //判断是否有为关闭的子类(一级)
              $bool = $this->_pickManager->getTypeHasChildren($data['id']);
              if ($bool)
                  return $this->renderJson(['status' => 0, 'msg' => '当前分类存在未停用的子类!']);*/
            //關閉全部子類
            $childrenIds = $this->_pickManager->pickTypeChildren($data['id']);
            $childrenNumber = $this->_pickManager->getTypeAllList(['and', ['status' => 1], ['in', 'id', $childrenIds]]);
            if ($childrenNumber) {
                $tr = \Yii::$app->db->beginTransaction();
                $result = $this->_pickManager->updateDepartmentType(['status' => 0], ['in', 'id', $childrenIds], false);
                $res = $this->_pickManager->updateDepartmentType($data, ['id' => $data['id']]);
                if ($result && $res) {
                    $tr->commit();
                    return $this->renderJson(['status' => 1, 'msg' => '修改成功']);
                } else {
                    $tr->rollBack();
                    return $this->renderJson(['status' => 0, 'msg' => '修改失败！']);
                }
            }
        }
        $res = $this->_pickManager->updateDepartmentType($data, ['id' => $data['id']]);
        if ($res)
            return $this->renderJson(['status' => 1, 'msg' => '修改成功']);
        return $this->renderJson(['status' => 0, 'msg' => '修改失败，请刷新后重试！']);
    }

    //删除类别
    public function actionDestroyepartmenttypeedit()
    {
        $post = \Yii::$app->request->post();
        if (empty($post['id']))
            return $this->remderJson(['status' => 0, 'msg' => '请刷新一下页面！']);
        $data['id'] = $post['id'];
        $res = $this->_pickManager->getTypeList($data['id'], "");
        if (!empty($res)) {
            return $this->renderJson(['status' => 0, 'msg' => '请先删除子分类！']);
        }
        $at = $this->_pickManager->getSummaryPermissions();
        if (empty($at))
            return false;
        if (empty($at['department_type_edit']))
            return false;
        $result = $this->_pickManager->getTypeOneId($data['id']);
        if ($result['pid'] === '0')
            return $this->renderJson(['status' => 0, 'msg' => '三大類不能刪除!']);
        $data['is_del'] = 0;
        $res = $this->_pickManager->updateDepartmentType($data, ['id' => $data['id']]);
        if ($res == false)
            return $this->renderJson(['status' => 0, 'msg' => '删除失败，请刷新后重试！']);
        return $this->renderJson(['status' => 1, 'msg' => '删除成功']);
    }
    /*-------------------------------------------- 部门类别编辑 END -------------------------------------------------------*/
    /*-------------------------------------------- 历史记录 START ---------------------------------------------------------*/
//修改历史
    public function actionHistory()
    {
        return $this->render('history', ['date' => date("Y-m")]);
    }

    public function actionHistorylist()
    {
        $psl_date_month = \Yii::$app->request->get('h_date_month');
        $month = empty($psl_date_month) ? date("Y-m", time()) : str_replace('/', '-', $psl_date_month);
        $time['start'] = strtotime($month) - 1;
        $time['end'] = strtotime("$month +1 month -1 day") + 86400;
        $aData = $this->_pickManager->GetHistory($time);
        $aData = PickData::toAllTimeData($aData);
        return $this->renderJson($aData);
    }

//删除历史
    public function actionDestroyhistory()
    {
        return $this->render('destroyhistory', ['date' => date("Y-m")]);
    }

    public function actionDestroyhistorylist()
    {
        $psl_date_month = \Yii::$app->request->get('hd_date_month');
        $month = empty($psl_date_month) ? date("Y-m", time()) : str_replace('/', '-', $psl_date_month);
        $time['start'] = strtotime($month) - 1;
        $time['end'] = strtotime("$month +1 month -1 day") + 86400;
        $aData = $this->_pickManager->getDestroyHistory($time);
        $aData = PickData::toAllTimeData($aData);
        return $this->renderJson($aData);
    }

    public function actionNotratinghistory()
    {
        $time['start'] = date('Y-m-d', strtotime('-6 days'));
        $time['end'] = date('Y-m-d', time());
        return $this->render("notratinghistory", ['date' => $time]);
    }

    //未评级四大类历史
    public function actionNotratinghistorylist()
    {
        $NRHDate = \Yii::$app->request->post();
        $dateStart = empty($NRHDate['dateStart']) ? date('Y-m-d', strtotime('-6 days')) : str_replace('/', '-', $NRHDate['dateStart']);
        $dateEnd = empty($NRHDate['dateEnd']) ? date("Y-m-d") : str_replace('/', '-', $NRHDate['dateEnd']);
        $time['start'] = strtotime($dateStart) - 1;
        $time['end'] = strtotime($dateEnd) + 86400;
        $aData = $this->_pickManager->NotRatingHistory($time);
        $aData = PickData::toTimeDate($aData);
        return $this->renderJson($aData);
    }
    /*-------------------------------------------- 历史记录 END -----------------------------------------------------------*/
    /*-------------------------------------------- 代理组长 STATUS --------------------------------------------------------*/
    public function actionAccredit()
    {
        $select = $this->_pickManager->Accredit();
        return $this->render("accredit", ['select' => $select]);
    }

    public function actionSaveaccredit()
    {
        $bool = $this->_pickManager->That();
        if ($bool === false)
            return $this->renderJson(["status" => 0, "msg" => "网络错误，请刷新重试！"]);
        $post = \Yii::$app->request->post();
        if (empty($post)) {
            $sStaffID_PD = '';
        } else {
            $sStaffID_PD = implode('.', $post['staff']);
        }
        $result = $this->_pickManager->SaveAccredit($sStaffID_PD);
        if ($result)
            return $this->renderJson(["status" => 1, "msg" => "修改成功"]);
        return $this->renderJson(["status" => 0, "msg" => "添加失败"]);

    }
    /*-------------------------------------------- 代理组长 END -----------------------------------------------------------*/
    /*-------------------------------------------- 权限设置 STATUS --------------------------------------------------------*/
    public function actionButtonauth()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        return $this->render("buttonauth");
    }

    /**
     * 部门类别可编辑人员设置
     */
    public function actionSetdepartmenttypeedit()
    {
        $staffs = $this->_pickManager->getDepartmentTypeEditStaffs();
        return $this->renderJson($staffs);
    }

    /**
     * 添加部门类别可编辑人员
     */
    public function actionAdddepartmenteditstaff()
    {
        $userId = \Yii::$app->request->post('username');
        if (empty($userId))
            return $this->renderJson(['status' => 0, 'msg' => '网络异常！']);
        $bool = $this->_pickManager->addDepartmentTypeEditStaff($userId);
        if ($bool)
            return $this->renderJson(['status' => 1, 'msg' => '添加成功！']);
        return $this->renderJson(['status' => 0, 'msg' => '网络异常！']);
    }

    /**
     * 删除部门类别可编辑人员
     */
    public function actionDestroydepartmenteditstaff()
    {
        $id = \Yii::$app->request->post('id');
        $bool = $this->_pickManager->destroyDepartmentEditStaff($id);
        if ($bool)
            return $this->renderJson(['status' => 1, 'msg' => '删除成功！']);
        return $this->renderJson(['status' => 0, 'msg' => '网络异常！']);
    }

    /*------------------------------------------ 代理组长设置  START-------------------------------------------------------*/
    public function actionAgent()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        return $this->render("agent");
    }

    public function actionAgentlist()
    {
        $aData = $this->_pickManager->getAgentUserList();
        return $this->renderJson($aData);
    }

    public function actionAuthorizationview()
    {
        $get = \Yii::$app->request->get('id');
        $aData = $this->_pickManager->getAgentList(['cn_staff.user_id' => $get]);
        $AobtainID = "";
        if (!empty($aData[0]['permissions_distribution']))
            $AobtainID = explode('.', $aData[0]['permissions_distribution']);
        return $this->render('authorizationView', ['obtain' => $AobtainID, 'id' => $get]);
    }

    public function actionGetagentstaff()
    {
        $aData = $this->_pickManager->getAgentStaff();
        return $this->renderJson($aData);
    }

    //设置授权
    public function actionSetagent()
    {
        $post = \Yii::$app->request->post();
        if (empty($post['id']))
            return $this->renderJson(['status' => 0, 'msg' => '设置失败，请刷新重试']);
        if (!empty($post['id'])) {
            if (!empty($post['users'])) {

                $data['id'] = $post['id'];
                foreach ($post['users'] as $k => $v) {
                    $data['authorization'][] = is_array($v) ? $v['id'] : $v;
                }
                $res = $this->_pickManager->setAgentUser($data);
                if ($res)
                    return $this->renderJson(['status' => 1, 'msg' => '设置成功']);
            }
        }
        return $this->renderJson(['status' => 0, 'msg' => '设置失败，请刷新重试']);
    }

    //删除代理
    public function actionDelagent()
    {
        $id = \YII::$app->request->post('id');
        $bool = $this->_pickManager->delAgentUser($id);
        if ($bool)
            return $this->renderJson(['status' => 1, 'msg' => '删除成功']);
        return $this->renderJson(['status' => 0, 'msg' => '删除失败']);
    }

    //新增人员
    public function actionAddagent()
    {
        $post = \Yii::$app->request->post();
        if (!empty($post['username'])) {
            $data['id'] = $post['username'];
            if (!empty($post['users'])) {
                foreach ($post['users'] as $k => $v) {
                    $data['authorization'][] = is_array($v) ? $v['id'] : $v;
                }
//                $data['authorization'] = trim(implode('.', $data['authorization']), '.');
                $bool = $this->_pickManager->AddAgent($data['id']);
                if ($bool)
                    $bool = $this->_pickManager->setAgent($data);
                if ($bool)
                    return $this->renderJson(['status' => 1, 'msg' => '新增成功']);
            }
        }
        return $this->renderJson(['status' => 0, 'msg' => '新增失败，请刷新']);
    }
    /*------------------------------------------ 代理组长设置  END  ---------------------------------------------------*/
    /*------------------------------------------ 未评五大类  STATUS ---------------------------------------------------*/
    /**
     * 展示未评五大类界面
     */
    public function actionShownotcommentedfivestype()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        return $this->render('notcommentedfivestype');
    }

    /**
     * 获取未评五大类已授权list
     */
    public function actionNotcommentedfivestypelist()
    {
        $staffs = $this->_pickManager->getNotCommentedFivesTypeList();
        return $this->renderJson($staffs);
    }

    /**
     * 更新未评五大类授权
     */
    public function actionUpdatenotcommentedfivestype()
    {
        $post = \Yii::$app->request->post();
        if (empty($post['id']))
            return $this->renderJson(['status' => 0, 'msg' => '网络错误！']);
        $where['id'] = $post['id'];
        if (isset($post['departments'])) {
            foreach ($post['departments'] as $k => $v) {
                $data['not_rating_history_units'][] = is_array($v) ? $v['id'] : $v;
            }
            $data['not_rating_history_units'] = trim(implode('.', $data['not_rating_history_units']), '.');
        } else {
            $data['not_rating_history_units'] = '';
        }
        $bool = $this->_pickManager->updateNotCommentedFivesTypeList($data, $where);
        if ($bool)
            return $this->renderJson(['status' => 1, 'msg' => '修改成功！']);
        return $this->renderJson(['status' => 0, 'msg' => '修改失败！']);
    }

    /**
     * 新增未评五大类授权
     */
    public function actionCreatenotcommentedfivestype()
    {
        $post = \Yii::$app->request->post();
        if (!empty($post['username'])) {
            $data['user_id'] = $post['username'];
            if (isset($post['departments'])) {
                foreach ($post['departments'] as $k => $v) {
                    $data['not_rating_history_units'][] = is_array($v) ? $v['id'] : $v;
                }
                $data['not_rating_history_units'] = trim(implode('.', $data['not_rating_history_units']), '.');
            } else {
                $data['not_rating_history_units'] = '';
            }
            $bool = $this->_pickManager->createdNotCommentedFivesType($data);
            if ($bool)
                return $this->renderJson(['status' => 1, 'msg' => '新增成功！']);
        }
        return $this->renderJson(['status' => 0, 'msg' => '新增失败！']);
    }

    /**
     * 删除未评五大类授权
     */
    public function actionDestroynotcommentedfivestype()
    {
        $id = \Yii::$app->request->post('id');
        if (!empty($id)) {
            $bool = $this->_pickManager->destroyNotCommentedFivesType($id);
            if ($bool)
                return $this->renderJson(['status' => 1, 'msg' => '删除成功！']);
        }
        return $this->renderJson(['status' => 0, 'msg' => '删除失败！']);
    }

    /*------------------------------------------ 未评五大类  END -----------------------------------------------------*/
    /*------------------------------------------ 历史记录  STATUS ----------------------------------------------------*/
    /**
     * 展示历史记录维护权限界面
     **/
    public function actionShowhistoryrecord()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        return $this->render('historyrecord');
    }

    /**
     * 获取查看历史记录已授权list
     */
    public function actionHistoryrecordlist()
    {
        $staffs = $this->_pickManager->getHistoryRecordList();
        return $this->renderJson($staffs);
    }

    /**
     * 更新查看历史记录授权
     */
    public function actionUpdatehistoryrecord()
    {
        $post = \Yii::$app->request->post();
        if (empty($post['id']))
            return $this->renderJson(['status' => 0, 'msg' => '网络错误！']);
        $where['id'] = $post['id'];
        if (isset($post['departments'])) {
            foreach ($post['departments'] as $k => $v) {
                $data['history_units'][] = is_array($v) ? $v['id'] : $v;
            }
            $data['history_units'] = trim(implode('.', $data['history_units']), '.');
        } else {
            $data['history_units'] = '';
        }
        $bool = $this->_pickManager->updateHistoryRecord($data, $where);
        if ($bool)
            return $this->renderJson(['status' => 1, 'msg' => '修改成功！']);
        return $this->renderJson(['status' => 0, 'msg' => '修改失败！']);
    }

    /**
     * 新增查看历史记录授权
     */
    public function actionCreatehistoryrecord()
    {
        $post = \Yii::$app->request->post();
        if (!empty($post['username'])) {
            $data['user_id'] = $post['username'];
            if (isset($post['departments'])) {
                foreach ($post['departments'] as $k => $v) {
                    $data['history_units'][] = is_array($v) ? $v['id'] : $v;
                }
                $data['history_units'] = trim(implode('.', $data['history_units']), '.');
            } else {
                $data['history_units'] = '';
            }
            $bool = $this->_pickManager->createdHistoryRecord($data);
            if ($bool)
                return $this->renderJson(['status' => 1, 'msg' => '新增成功！']);
        }
        return $this->renderJson(['status' => 0, 'msg' => '新增失败！']);
    }

    /**
     * 删除查看历史记录授权
     */
    public function actionDestroyhistoryrecord()
    {
        $id = \Yii::$app->request->post('id');
        if (!empty($id)) {
            $bool = $this->_pickManager->destroyHistoryRecord($id);
            if ($bool)
                return $this->renderJson(['status' => 1, 'msg' => '删除成功！']);
        }
        return $this->renderJson(['status' => 0, 'msg' => '删除失败！']);
    }
    /*------------------------------------------ 历史记录  END -------------------------------------------------------*/
    /*------------------------------------------ 总汇维护界面  STATUS ------------------------------------------------*/
    public function actionShowsummarymaintain()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        return $this->render('summarymaintain');
    }

    /**
     * 获取查看已授权总汇list
     */
    public function actionSummarymaintainlist()
    {
        $staffs = $this->_pickManager->getSummaryMaintainList();
        return $this->renderJson($staffs);
    }

    /**
     * 新增总汇授权
     */
    public function actionCreatesummarymaintain()
    {
        $post = \Yii::$app->request->post();
        if (!empty($post['username'])) {
            $data['user_id'] = $post['username'];
            if (isset($post['departments'])) {
                foreach ($post['departments'] as $k => $v) {
                    $data['unit_id'][] = is_array($v) ? $v['id'] : $v;
                }
                $data['unit_id'] = trim(implode('.', $data['unit_id']), '.');
            } else {
                $data['unit_id'] = '';
            }
            $bool = $this->_pickManager->createdSummaryMaintain($data);
            if ($bool)
                return $this->renderJson(['status' => 1, 'msg' => '新增成功！']);
        }
        return $this->renderJson(['status' => 0, 'msg' => '新增失败！']);
    }

    /**
     * 更新查看总汇部门授权
     */
    public function actionUpdatesummarymaintain()
    {
        $post = \Yii::$app->request->post();
        if (empty($post['id']))
            return $this->renderJson(['status' => 0, 'msg' => '网络错误！']);
        $where['id'] = $post['id'];
        if (isset($post['departments'])) {
            foreach ($post['departments'] as $k => $v) {
                $data['unit_id'][] = is_array($v) ? $v['id'] : $v;
            }
            $data['unit_id'] = trim(implode('.', $data['unit_id']), '.');
        } else {
            $data['unit_id'] = '';
        }
        $bool = $this->_pickManager->updateSummaryMaintain($data, $where);
        if ($bool)
            return $this->renderJson(['status' => 1, 'msg' => '修改成功！']);
        return $this->renderJson(['status' => 0, 'msg' => '修改失败！']);
    }

    /**
     * 删除查看总汇部门授权
     */
    public function actionDestroysummarymaintain()
    {
        $id = \Yii::$app->request->post('id');
        if (!empty($id)) {
            $bool = $this->_pickManager->destroySummaryMaintain($id);
            if ($bool)
                return $this->renderJson(['status' => 1, 'msg' => '删除成功！']);
        }
        return $this->renderJson(['status' => 0, 'msg' => '删除失败！']);
    }
    /*------------------------------------------ 总汇维护界面  END ----------------------------------------------------*/
    /*------------------------------------------ 总汇管理层维护界面  STATUS -------------------------------------------*/
    public function actionShowsummarymanagement()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        return $this->render('summarymanagement');
    }

    /**
     * 总汇管理层可查看人员设置
     */
    public function actionReadsummarymanagement()
    {
        $staffs = $this->_pickManager->getSummaryManagementStaffs();
        return $this->renderJson($staffs);
    }

    /**
     * 添加总汇管理层可查看人员设置
     */
    public function actionCreatesummarymanagement()
    {
        $userId = \Yii::$app->request->post('username');
        if (empty($userId))
            return $this->renderJson(['status' => 0, 'msg' => '网络异常！']);
        $bool = $this->_pickManager->createSummaryManagementStaff($userId);
        if ($bool)
            return $this->renderJson(['status' => 1, 'msg' => '添加成功！']);
        return $this->renderJson(['status' => 0, 'msg' => '网络异常！']);
    }

    /**
     * 删除总汇管理层可查看人员
     */
    public function actionDestroysummarymanagement()
    {
        $id = \Yii::$app->request->post('id');
        $bool = $this->_pickManager->destroySummaryManagementStaff($id);
        if ($bool)
            return $this->renderJson(['status' => 1, 'msg' => '删除成功！']);
        return $this->renderJson(['status' => 0, 'msg' => '网络异常！']);
    }
    /*------------------------------------------ 总汇管理层维护界面  END ----------------------------------------------*/
    /*------------------------------------------ 权限维护维护界面  STATUS ---------------------------------------------*/
    /**
     * 前台权限设置界面
     */
    public function actionShowauthmanagement()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        return $this->render('authmanagement');
    }

    /**
     * 获取权限管理人员
     */
    public function actionReadauthmanagement()
    {
        $staffs = $this->_pickManager->getAuthManagementStaffs();
        return $this->renderJson($staffs);
    }

    /**
     * 添加权限管理人员
     */
    public function actionCreateauthmanagement()
    {
        $userId = \Yii::$app->request->post('username');
        if (empty($userId))
            return $this->renderJson(['status' => 0, 'msg' => '网络异常！']);
        $bool = $this->_pickManager->createAuthManagementStaff($userId);
        if ($bool)
            return $this->renderJson(['status' => 1, 'msg' => '添加成功！']);
        return $this->renderJson(['status' => 0, 'msg' => '网络异常！']);
    }

    /**
     * 删除权限管理人员
     */
    public function actionDestroyauthmanagement()
    {
        $id = \Yii::$app->request->post('id');
        $bool = $this->_pickManager->destroyAuthManagementStaff($id);
        if ($bool)
            return $this->renderJson(['status' => 1, 'msg' => '删除成功！']);
        return $this->renderJson(['status' => 0, 'msg' => '网络异常！']);
    }
    /*------------------------------------------ 权限维护维护界面  END ------------------------------------------------*/
    /*------------------------------------------ 被影響人負責人维护界面  START ----------------------------------------*/
    //打開 被影響負責人界面
    public function actionShowaffectprincipal()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        return $this->render('affectprincipal');
    }

    //獲取被影響負責人 list數據
    public function actionAffectprincipallist()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        $data = $this->_pickManager->getAffectPrincipal();
        return $this->renderJson($data);
    }

    //添加被影響負責人數據
    public function actionAffectprincipalstore()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        $post = \Yii::$app->request->post();
        $data['user_id'] = $post['username'];
        $departmentIds = [];
        if (!empty($post['affected_group'])) {
            foreach ($post['affected_group'] as $k => $v) {
                $data['affected_group'][] = $v['id'];
            }
            $departmentIds = $this->_pickManager->getGroupBelongToDepartment($data['affected_group']);
            $data['affected_group'] = implode('.', $data['affected_group']);
        }
        if (!empty($post['affected_department'])) {
            foreach ($post['affected_department'] as $k => $v) {
                $data['affected_department'][] = $v['id'];
            }
            $data['affected_department'] = array_diff($data['affected_department'], $departmentIds);
            $data['affected_department'] = implode('.', $data['affected_department']);
        }
        $result = $this->_pickManager->affectPrincipalStore($data);
        if ($result)
            return $this->renderJson(['status' => 1, 'msg' => '添加成功！']);
        return $this->renderJson(['status' => 0, 'msg' => '添加失敗！']);
    }

    //更新被影響負責人
    public function actionAffectprincipalupdate()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        $post = \Yii::$app->request->post();
        $data['id'] = $post['id'];
        $departmentIds = [];
        if (!empty($post['affected_group'])) {
            foreach ($post['affected_group'] as $k => $v) {
                if (isset($v['id'])) {
                    $data['affected_group'][] = $v['id'];
                } else {
                    $data['affected_group'][] = $v;
                }
            }
            $departmentIds = $this->_pickManager->getGroupBelongToDepartment($data['affected_group']);
            $data['affected_group'] = implode('.', $data['affected_group']);
        } else {
            $data['affected_group'] = '';
        }
        if (!empty($post['affected_department'])) {
            foreach ($post['affected_department'] as $k => $v) {
                if (isset($v['id'])) {
                    $data['affected_department'][] = $v['id'];
                } else {
                    $data['affected_department'][] = $v;
                }
            }
            $data['affected_department'] = array_diff($data['affected_department'], $departmentIds);
            $data['affected_department'] = implode('.', $data['affected_department']);
        }
        $result = $this->_pickManager->affectPrincipalUpdate($data);
        if ($result)
            return $this->renderJson(['status' => 1, 'msg' => '更新成功！']);
        return $this->renderJson(['status' => 0, 'msg' => '更新失敗！']);
    }

    //刪除被影響負責人
    public function actionAffectprincipaldestory()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        $data['id'] = \Yii::$app->request->post('id');
        $data['affected_department'] = '';
        $data['affected_group'] = '';
        $result = $this->_pickManager->affectPrincipalUpdate($data);
        if ($result)
            return $this->renderJson(['status' => 1, 'msg' => '刪除成功！']);
        return $this->renderJson(['status' => 0, 'msg' => '刪除失敗！']);

    }
    /*------------------------------------------ 被影響人負責人维护界面  END ------------------------------------------*/
    /*------------------------------------------ 评级设置维护界面  END ------------------------------------------------*/
    public function actionShowratingsettings()
    {
        $auth = $this->_pickManager->isAuthManagement();
        if (!$auth)
            return false;
        return $this->render('ratingsettings');
    }

    /**
     * 获取可评级设置list
     **/
    public function actionRatingsettingslist()
    {
        $data = $this->_pickManager->getDepartmentRating();
        return $this->renderJson($data);
    }

    /**
     * 设置评级部门
     **/
    public function actionUpdateratingsettings()
    {
        $post = \Yii::$app->request->post();
        if (!empty($post['departmentId'])) {
            if (!empty($post['departmentStatus'])) {
                $data['unit_id'] = $post['departmentId'];
                $data['bool'] = $post['departmentStatus'] === 'true' ? true : false;
                $bool = $this->_pickManager->onDepartmentRating($data);
                return $this->renderJson(['status' => 1, 'msg' => '设置成功！']);
            }
        }
        return $this->renderJson(['status' => 0, 'msg' => '设置失败！']);
    }
    /*------------------------------------------ 评级设置维护界面  END ------------------------------------------------*/
    /*------------------------------------------ public STATUS -------------------------------------------------------*/
    /**
     * 获取部门信息 key value
     */
    public function actionGetdepartment()
    {
        $department = $this->_pickManager->company(4, 1);
        $departments = [];
        foreach ($department as $k => $v) {
            $departments[$k]['id'] = $v['id'];
            $departments[$k]['name'] = $v['unit_name'];
        }
        return $this->renderJson($departments);
    }

    /**
     * 获取中國部门信息 key value group
     */
    public function actionGetgroupdepartment()
    {
        $country = $this->_pickManager->company(8, 1);
        $departments = $this->groupDepartment($country);
        return $this->renderJson($departments);
    }

    /**
     * 获取部门信息 key value group
     */
    public function actionGroupdepartment()
    {
        $country = $this->_pickManager->company(8);
        $departments = $this->groupDepartment($country);
        return $this->renderJson($departments);
    }

    public function actionGetgroups()
    {
        $data = $this->_pickManager->getAllGroup();
        $_data = [];
        foreach ($data as $k => $v) {
            $_data[$k]['id'] = $v['id'];
            $_data[$k]['name'] = $v['unit_name'];
        }
        return $this->renderJson($_data);
    }

    /***
     * 被影響人：情況1、根據獲取權限獲取，組list 情況2、獲取全部權限之外的，組list 情況3、獲取所有組
     * filter 0 ：獲取不存在權限的組別 1：獲取存在權限的組別 其他：獲取全部組別
     * @return string
     */
    public function actionAffectedgroup()
    {
        $affectedDepartment = \Yii::$app->request->post('affectedDepartment');
        $filter = \Yii::$app->request->post('filter');
        if ($affectedDepartment && is_array($affectedDepartment)) {
            if ($filter){
                $userAuth = $this->_pickManager->getSummaryPermissions();
                $userAuth['affected_department'] = explode('.',$userAuth['affected_department']);
                $userAuth['affected_group'] = explode('.',$userAuth['affected_group']);
                $affectedDepartments = [];//能獲取的部門
                $_affectedDepartments = [];//未知能獲取的部門
                foreach($affectedDepartment as $k => $v){
                    if (in_array($v,$userAuth['affected_department'])){
                        $affectedDepartments[] = $v;
                    }else{
                        $_affectedDepartments[] = $v;
                    }
                }
                $unitId = $this->_pickManager->getGroupBelongToDepartment($userAuth['affected_group']);
                foreach ($_affectedDepartments as $k=>$v){
                    if (!in_array($v,$unitId)){
                        unset($_affectedDepartments[$k]);
                    }
                }
                $_affectedDepartments = array_values($_affectedDepartments);//只有組別的權限的部門
                $where = [
                    'and',
                    ['=', 'cn_unit.type', 4],
                    ['=', 'cn_unit.is_active', 1],
                    ['in', 'cn_unit.id', $_affectedDepartments],
                    ['in','pp.id',$userAuth['affected_group']],
                    ['NOT', ['pp.id' => null]]
                ];
                $groupData = $this->_pickManager->getAffectedGroup($where);
            }else{
                $affectedDepartments = $affectedDepartment;
            }
            $where = [
                'and',
                ['=', 'cn_unit.type', 4],
                ['=', 'cn_unit.is_active', 1],
                ['in', 'cn_unit.id', $affectedDepartments],
                ['NOT', ['pp.id' => null]]
            ];
            $data = $this->_pickManager->getAffectedGroup($where);
            if (isset($groupData)){
                $data = array_merge($groupData,$data);
            }
        } elseif ($affectedDepartment == 'all') {
            $where = [
                'and',
                ['=', 'cn_unit.type', 4],
                ['=', 'cn_unit.is_active', 1],
                ['NOT', ['pp.id' => null]]
            ];
            $data = $this->_pickManager->getAffectedGroup($where);
        } else {
            $data = [];
        }
        return $this->renderJson($data);
    }

    /**
     * @param $country array 部門信息
     * @return array
     */
    public function groupDepartment($country)
    {
        $i = 0;
        $departments = [];
        $country = $this->_pickManager->getUnit([]);
        $department = $this->_pickManager->groupDepartment($country);
        foreach ($department as $k1 => $v1) {
            $departments[$i]['id'] = $v1['id'];
            $departments[$i]['name'] = str_replace("<br>", "", $v1['unit_name']);
            $departments[$i]['group'] = str_replace("<br>", "", $v1['group']);
            $departments[$i]['groupId'] = $v1['groupId'];
            $departments[$i]['hasChildren'] = isset($v1['hasChildren']) ? $v1['hasChildren'] : false;
            $i++;
        }
        return $departments;
    }

    /**
     * 获取部门人员消息
     */
    public function actionGetdepartmentstaffs()
    {
        $department = \Yii::$app->request->get('department');
        $staffs = $this->_pickManager->getDepartmentStaffs($department);
        $staff = [];
        foreach ($staffs as $k => $v) {
            $staff[$k]['id'] = $v['user_id'];
            $staff[$k]['name'] = $v['username'];
        }
        return $this->renderJson($staff);
    }

    /**
     * 获取人员信息 key value
     **/
    public function actionGetstaffs()
    {
        $where = [
            'and',
            ['not', ['user_id' => null]],
            ['not', ['user_id' => '']]
        ];
        $staffs = $this->_pickManager->getStaffs($where);
        $staff = [];
        foreach ($staffs as $k => $v) {
            $staff[$k]['id'] = $v['user_id'];
            $staff[$k]['name'] = $v['username'];
        }
        return $this->renderJson($staff);
    }

    /**
     * 获取人员信息和部門信息
     **/
    public function actionDepartmentstaffs()
    {
        $where = [
            'and',
            ['not', ['user_id' => null]],
            ['not', ['user_id' => '']]
        ];
        $staffs = $this->_pickManager->getStaffs($where);
        $staff = [];
        foreach ($staffs as $k => $v) {
            $staff[$k]['id'] = $v['user_id'];
            $staff[$k]['name'] = $v['username'];
            $staff[$k]['department_name'] = str_replace("<br>", "", $v['department_name']);
            $staff[$k]['department_id'] = $v['department_id'];
            $staff[$k]['group_name'] = empty($v['group_name']) ? "無" : str_replace("<br>", "", $v['group_name']);
            $staff[$k]['group_id'] = $v['group_id'];
        }
        return $this->renderJson($staff);
    }

    public function actionGetleaderstaffs()
    {
        $leaderId = $this->_pickManager->getLeaderId();
        $where = [
            'and',
            ['in', 'cn_staff.id', $leaderId],
            [
                'and',
                ['not', ['user_id' => null]],
                ['not', ['user_id' => '']]
            ]
        ];
        $staffs = $this->_pickManager->getStaffs($where);
        $staff = [];
        foreach ($staffs as $k => $v) {
            $staff[$k]['id'] = $v['user_id'];
            $staff[$k]['name'] = $v['username'];
        }
        return $this->renderJson($staff);
    }
    /*------------------------------------------ public  END ---------------------------------------------------------*/
    /*------------------------------------------ 被影響人  START -----------------------------------------------------*/
    //被影響人 界面
    public function actionShowaffectedstaff()
    {
        $firstDay = date('Y-m-d');
        $date['start'] = date("Y-m-d", strtotime("-4 day"));
        $date['end'] = $firstDay;
        $auth = $this->_pickManager->getSummaryPermissions();
        $department = empty($auth['affected_department']) ? [] : explode('.', $auth['affected_department']);
        $group = empty($auth['affected_group']) ? [] : explode('.', $auth['affected_group']);
        $authGroupIds = $this->_pickManager->canSelectAffectedGroup($department, $group);
        $userAuth['affected_department'] = $department;
        $userAuth['affected_group'] = $authGroupIds;
        return $this->render("affectedstaff", ['date' => $date, 'userAuth' => $userAuth]);
    }

    //被影響人數據
    public function actionAffectedpeople()
    {
        $get = \Yii::$app->request->get();
        $date['start'] = empty($get['dateStart']) ? strtotime("-4 day") - 1 : strtotime($get['dateStart']) - 1;
        $date['end'] = empty($get['dateEnd']) ? strtotime("+1 day") : strtotime($get['dateEnd']) + 86400;
        $affectedPeople = $this->_pickManager->affectedPeople($date);
        return $this->renderJson($affectedPeople);
    }

    //獲取tree staff
    public function actionGettreeviewstaff()
    {
        $affectedDepartment = \Yii::$app->request->post('affectedDepartment');
        $affectedGroup = \Yii::$app->request->post('affectedGroup');
        if (empty($affectedDepartment) && !is_array($affectedDepartment)){
            return $this->renderJson([]);
        }
        $userAuth = $this->_pickManager->getSummaryPermissions();
        $userAuth['affected_department'] = explode('.', $userAuth['affected_department']);
        $userAuth['affected_group'] = explode('.', $userAuth['affected_group']);
        $userAuth['affected_group_all'] = $this->_pickManager->canSelectAffectedGroup($userAuth['affected_department'],$userAuth['affected_group']);
        foreach ($affectedDepartment as $k => $v) {
            if (!in_array($v, $userAuth['affected_department'])) {
                unset($affectedDepartment[$k]);
            }
        }
        $affectedDepartment = array_values($affectedDepartment);
        if (is_array($affectedGroup)) {
            foreach ($affectedGroup as $k => $v) {
                if (!in_array($v, $userAuth['affected_group_all'])) {
                    unset($affectedGroup[$k]);
                }
            }
            $affectedGroup = array_values($affectedGroup);
        }
        $group = $this->_pickManager->getUnit(["id" => $affectedGroup]);
        $groupData = [];
        foreach ($group as $k => $v) {
            $groupData[$v['parent_id']][] = $v['id'];
            $affectedDepartment[] = $v['parent_id'];
        }
        $departments = $this->_pickManager->getUnit(["id" => $affectedDepartment]);
        $topData = [];
        foreach ($departments as $k => $v) {
            $topData[$k]['id'] = $v['id'];
            $topData[$k]['type'] = $v['type'];
            $topData[$k]['name'] = $v['unit_name'];
        }
        $data = $this->_pickManager->treeViewOrganizationStaff($topData, $groupData);
        return $this->renderJson($data);
    }

    //更新被影響人（包含被影響、部門、組別）
    public function actionUpdateaffected()
    {
        $post = \Yii::$app->request->post();
        $result = $this->_pickManager->updateAffected($post);
        if (isset($result['status']))
            return $this->renderJson(["status" => 0, "info" => $result['info']]);
        if ($result)
            return $this->renderJson(["status" => 1, "info" => "更新成功！","update_data"=>$result]);
        return $this->renderJson(["status" => 0, "info" => '更新失敗！']);
    }
    /*--------------------------------------------- 被影響人  END --------------------------------------------------------*/
    /*--------------------------------------------- 績效影響  START ------------------------------------------------------*/
//展示績效影響界面
    public function actionShowpickaffected()
    {
        return $this->render('pickaffected', ['month' => date("Y-m")]);
    }

//獲取績效影響數據
    public function actionPickaffectedlist()
    {
        $month = \Yii::$app->request->post('month');
        if (!($data['start'] = strtotime($month))) {
            $data['start'] = strtotime(date("Y-m"));
        }
        $data['end'] = strtotime("+1months", $data['start']);
        $data = $this->_pickManager->pickAffected($data);
        return $this->renderJson($data);
    }

    /*--------------------------------------------- 績效影響  END --------------------------------------------------------*/
    public function actionTest()
    {
        $this->_pickManager->unit();
    }
}
